<template>
	<view class="map-box">
		<!-- <MapTest style="width: 710rpx; height: 250px;" /> -->
		<view class="map_tisp" @click="paste()" v-if="false">
			当前所在机器经纬度：点击可复制<br/>
			latitude: {{latitude}}  longitude: {{longitude}}
		</view>
		<view v-if="isShowMap">
			<view id="activeMap">
				<view @tap="activeMarker={}">
					<view class="page-body map-view" style="z-index: 1;position: relative;">
						<view class="page-section page-section-gap map-view">
							<map class="map-box-cont" :markers="list" id="miniMap" :scale="prevScale" :show-location="true" :latitude="latitude" :longitude="longitude" @regionchange="regionChange"
							 @markertap="markerTap" @tap="activeMarker={}">
								<!-- @markertap 点击标记点时触发，e.detail = {markerId}-->
								<!-- @tap 点击地图时触发-->
								<!-- @regionchange 视野发生变化时触发-->
								<cover-image class="manpCenter" src="../../static/userposition.png"></cover-image>
							</map>
							<!-- <cover-image class="map-image" src="../../static/address.png"></cover-image> -->
						</view>
					</view>
				</view>
			</view>
			<view class="f-cont" v-show="cardInfo.name">
				<view class="info">
					<image :src="cardInfo.positionPic" class="img" mode=""></image>
					<view class="r-info">
						{{cardInfo.name}}
						<view class="time mt">
							<image src="../../static/time1.png" class="s" mode=""></image>{{cardInfo.workTimes}}
						</view>
						<view class="time">
							<image src="../../static/wz.png" class="s" mode=""></image>{{cardInfo.address}}
						</view>
					</view>
				</view>
				<view class="foot-info">
					<image src="../../static/printer_active1.png" class="imgs" mode=""></image>
					{{list.length}}台打印机
					<view class="fr">
						<image @click="toMapAPP(cardInfo)" src="../../static/map_dh_bnt.png" class="dh" mode=""></image>
					</view>
				</view>
			</view>
		</view>
		<view v-else class="no-gps">
			<view v-if="isNo">
				未开启GPS无法使用附近功能
				<view class="fj-bnt" @tap="openGps">去开启</view>
			</view>
			<view class="no-gps-desc" v-else>
				<view class="location_indicator"></view>
				正在搜索您当前位置，请确保已开启GPS
			</view>
		</view>
		<Tabbar :current="1"></Tabbar>
	</view>
</template>

<script>
	import Tabbar from '@/components/tabBar.vue'
	// import MapTest from '@/components/mapTest.vue'
	const QQMapWX = require('@/utils/qqmap-wx-jssdk/qqmap-wx-jssdk.min.js');
	// 实例化API核心类
	const qqmapsdk = new QQMapWX({
	    key: 'RQVBZ-7D5WZ-RGQXH-TDNGS-LB5LK-OUB2C'//'FSUBZ-YR2LD-UOY4C-HY55B-JACU3-XBFFN' // 必填腾讯地图key
	});
	import { getGpsInfo, getNailTerminal } from '@/api/base.js'
	export default {
		components:{
			Tabbar,
			// MapTest
		},
		onUnload() {
			console.log('onUnload')
			clearInterval(this.intervalId);
			this.intervalId = null
		},
		onHide() {
			console.log('onHide')
			clearInterval(this.intervalId);
			this.intervalId = null
		},
		onShow() {
			this.isGetLocation()
			if(this.isGps) {
				this.getScale()
			}
		},
		onLaunch() {
			//隐藏官方的tabBar
			uni.hideTabBar()
		},
		data() {
			return {
				// 31.181649,121.429777
				// latitude: "27.257640",
				// longitude: "111.727125",
				// 31.375901,121.265401
				latitude: 31.229627,
				longitude: 121.472625,
				address: '',
				controls:[{
				    // 在地图上显示控件，控件不随着地图移动
				    id: 1, // 控件id
					iconPath:'../../static/icon.png', // 显示的图标
					position:{
					 // 控件在地图的位置
					 left: 15,
					 top: 15,
					 width: 50,
					 height: 50
				   },    
				}],
				list: [
				// 	{
				// 	id: 1264640,
				// 	user_id: 335187,
				// 	place: "上海市",
				// 	text: "dadaqianduan.cn",
				// 	latitude: 31.229627,
				// 	longitude: 121.472625,
				// 	status: "normal",
				// 	nickname: "dada",
				// 	iconPath: "../../static/printer3.png",
				// 	distance: 13419,
				// 	width: 36,   //宽
				// 	height: 46,   //高
				// },
				],
				shops: [],
				mapCtx: {},
				isGps: false,
				isShowMap: false,
				cardInfo: {},
				intervalId: null,
				prevScale: 16,
				isNo: false
			};
		},
		onLoad() {
				// console.log('触发显示页面事件');  
			    // var _this = this;  
			    // uni.getLocation({  
			    //     type: 'gcj02',  
			    //     success: function(res) {  
			    //         console.log('进入回调:success');  
			    //     },  
			    //     fail() {  
			    //         console.log('进入回调:fail');  
			    //     },  
			    //     complete() {  
			    //         console.log('进入回调:complete');  
			    //     }  
			    // });  
			    // console.log('结束事件');
				// this.getLocationInfo()
				// this.authorize()
				
				
				// 参考文档
				// https://blog.csdn.net/weixin_43245095/article/details/117817165
				
				// https://blog.csdn.net/znx981912/article/details/122082035
				
				// https://blog.csdn.net/weixin_45653970/article/details/119609883
				
				// 小程序地图API文档
				// https://developers.weixin.qq.com/miniprogram/dev/api/media/map/MapContext.getRegion.html
				
				// this.isGetLocation();
				//创建 map 上下文 MapContext 对象。
				this.mapCtx = wx.createMapContext('miniMap')
				//this.getRegionClick()
		},
		methods:{
			paste(value) {
				let copy = {
					latitude: this.latitude,
					longitude: this.longitude
				}
				uni.setClipboardData({
					data: JSON.stringify(copy)
				});
			},
			openGps(){
				this.getAuthorizeInfo()
			},
			// 获取当前地图的视野范围
			getRegionClick() {
				const that = this
			    this.mapCtx.getRegion({
					success: function (res) {
						// console.log(res,'------------获取当前地图的视野范围回传值-----------',res)
						console.log(res.southwest, '----西南角经纬度----')
						console.log(res.northeast, '----东北角经纬度----')
						let params = {
							// lat: 31.293829,
							// lng: 121.168058,
							// maxLatitude: 200, //res.southwest.latitude,
							// maxLongitude: 200, //res.southwest.longitude,
							// minLatitude: 1,//res.northeast.latitude,
							// minLongitude: 1,//res.northeast.longitude
							
							maxLatitude: res.northeast.latitude,//.toFixed(6),
							maxLongitude: res.northeast.longitude,//.toFixed(6),
							minLatitude: res.southwest.latitude,//.toFixed(6),
							minLongitude: res.southwest.longitude,//.toFixed(6)
							
							
							// maxLatitude: 31.293829,//res.southwest.latitude,
							// maxLongitude: 121.168058,//res.southwest.longitude,
							// minLatitude: 31.208562,//res.northeast.latitude,
							// minLongitude: 121.408795//res.northeast.longitude
						}
						that.getGpsInfoFn(params)
					}
			    })
				
				// this.mapCtx.includePoints({
				// 	success: function (res) {
				// 		console.log(res,'------------缩放视野展示所有经纬度-----------')
				// 	}
				// })
				
				// this.mapCtx.moveToLocation({
				// 	success: function (res) {
				// 		console.log(res,'------------将地图中心移置当前定位点，此时需设置地图组件 show-location 为true-----------')
				// 	}
				// })
				
				// this.mapCtx.openMapApp({
				// 	success: function (res) {
				// 		console.log(res,'------------拉起地图APP选择导航-----------')
				// 	}
				// })
				
				
				
				
			},
			// 查看是否已经授权定位
			isGetLocation(a = "scope.userLocation") { // 3. 检查当前是否已经授权访问scope属性，
				const _this = this;
				// #ifdef  MP-WEIXIN
				uni.getSetting({
					scope: a,
					success(res) {
						if (!res.authSetting[a]) { //3.1 每次进入程序判断当前是否获得授权，如果没有就去获得授权，如果获得授权，就直接获取当前地理位置
							_this.getAuthorizeInfo()
							console.log('授权成功')
						} else {
							_this.getLocationInfo()
							console.log('授权失败')
						}
					}
				});
				// #endif
			},
			getAuthorizeInfo(a = "scope.userLocation"){
				const _this = this;
				// 微信下授权弹窗
				uni.authorize({
					scope: a,
					success(res) { //1.1 允许授权
						console.log('允许授权-----------',res)
						_this.getLocationInfo();
					},
					fail() { //1.2 拒绝授权
						uni.showModal({
							content:'检测到您没打开获取信息功能权限，是否去设置打开？',
								confirmText: "确认",
								cancelText:'取消',
								success: (res) => {
									if(res.confirm){
										_this.isNo = false
										uni.openSetting({
											success: (res) => {
												_this.getLocationInfo();
											}
										})
									}else{
										uni.showToast({
											title: "你拒绝了授权",
											icon: 'none'
										})
										_this.isNo = true
										return false;
									}
								}
						})
					}
				})
			},
			getAddres(latitude,longitude) {
				let that = this;
				//逆地址解析  坐标转地址信息
				qqmapsdk.reverseGeocoder({
				  //Object格式
					location: {
						latitude,
						longitude
					}, 
					success: function(res) {//成功后的回调
					   const mapdata = res.result.ad_info;
					   console.log('mapdata', res.result.address)
					   that.address = res.result.address
				    },
					fail: function(error) {
					   console.error(error,'00001');
					},
					complete: function(res) {
					   // console.log(res,'00002');
					}
				});
			},
			// 获取定位授权
			getLocationInfo() {
				let that = this;
				uni.getLocation({
					type: 'gcj02',
					geocode: true,
					isHighAccuracy: true,//开启高精度定位默认false
					success: (res) => {
						// 当前IP：223.210.17.120
						console.log('-----当前定位信息-----', 'latitude：' + res.latitude, 'longitude：' + res.longitude)
						// console.log('latitude：' + res.latitude);
						// console.log('longitude：' + res.longitude);
						that.latitude = res.latitude
						that.longitude = res.longitude
						// 标记是否授权
						that.isGps = true
						that.isShowMap = true
						that.getScale()
						that.getRegionClick()
						// that.getAddres(res.latitude,res.longitude)
					},
					fail(f) {
						uni.showModal({
							content: '您没打开gps定位？获取位置失败',
							showCancel: false
						})
						that.isGps = false
					},  
					complete(c) {
					}  
				});
			},
			markerTap(e){
				console.log('--------markerTap---------',e)
				console.log('e.mp.detail.markerId',e.mp.detail.markerId)
				// @markertap-表示点击标记点时触发，e.detail={markerId}
				let markerId = e.detail.markerId
				let data = this.list
				data.forEach((item,index) => {
					if(index == markerId) {
						item.iconPath = '../../static/printer3.png'
						// this.getAddres(item.latitude,item.longitude)
						// that.moveMarkerToCenter(item)
						this.getNailTerminalFn(item.user_id)
					}else{
						item.iconPath = '../../static/printer3.png'
					}
				})
			},
			getGpsInfoFn(params) {
				getGpsInfo(params).then((res) => {
					let data = res
					let arr = []
					console.log('------------返回附近list----------------',res.length)
					data.forEach((ele,index) => {
						arr.push({
							id: index,
							user_id: ele.id,
							place: ele.name,
							address: ele.address,
							text: "dadaqianduan.cn",
							latitude: ele.lat,
							longitude: ele.lng,
							status: "normal",
							nickname: "dada",
							iconPath: "../../static/printer3.png",
							distance: 13419,
							width: 36,   //宽
							height: 46,   //高
						})
					})
					// this.latitude = data[0].lat
					// this.longitude = data[0].lng
					if(this.intervalId == null){
						this.getScale()
					}
					this.isShowMap = true
					this.list = arr
				})
			},
			getNailTerminalFn(id) {
				getNailTerminal({id}).then((res) => {
					this.cardInfo = res
				})
			},
			// https://blog.csdn.net/weixin_64132598/article/details/130699736 监听缩放
			// https://segmentfault.com/q/1010000041693472
			moveMarkerToCenter(marker) {
				const that = this
				//将marker移动至中心点
				this.mapCtx.moveToLocation({
					longitude: marker.longitude,
					latitude: marker.latitude,
					success: (res) => {
						//这里加300ms的延时是为了防止和moveToLocation功能冲突，保留地图移动的动画
						const timer = setTimeout(() => {
							that.longitude = marker.longitude;
							that.latitude = marker.latitude;
							clearTimeout(timer);
							//进行缩放，设置为16
							// this.scale = 16;
						}, 300);
					},
				});
			},
			// 监听缩放
			getScale() {
				const that = this
				this.intervalId = setInterval(() => {
					console.log('监听地图是否缩放')
				    this.mapCtx.getScale({
				        success:(res) => {
							if(res.scale > that.prevScale || res.scale < that.prevScale) {
								// console.log('-----触发缩放重新获取附近店-----',res.scale)
								// that.getRegionClick()
							}
							that.prevScale = res.scale
				        }
				    })
				}, 500)
			},
			// 移动地图后重新获取门店
			regionChange(e) {
				console.log('地图改变了')
				const that = this
				that.cardInfo.name = ''
				// 返回值分别是begin/end
				if(e.type === 'end') {
					this.shopTimeout = setTimeout(_ => {
						that.getRegionClick()
					}, 500)
				}
				return
				
				uni.createMapContext('miniMap', this).getCenterLocation({
					success: res => {
						console.log('移动地图后重新获取门店')
						console.log(res.latitude)
						console.log(res.longitude)
						this.shopTimeout = setTimeout(_ => {
							that.getRegionClick()
						}, 300)
					},
					fail: res => {
						uni.showModal({
							content: '获取位置失败',
							showCancel: false
						})
					}
				})
			},
			// 两点间距离
			distance(la1, lo1, la2, lo2) {
				var La1 = (la1 * Math.PI) / 180.0
				var La2 = (la2 * Math.PI) / 180.0
				var La3 = La1 - La2
				var Lb3 = (lo1 * Math.PI) / 180.0 - (lo2 * Math.PI) / 180.0
				var s =
					2 *
					Math.asin(
						Math.sqrt(
							Math.pow(Math.sin(La3 / 2), 2) +
							Math.cos(La1) * Math.cos(La2) * Math.pow(Math.sin(Lb3 / 2), 2)
						)
					)
				s = s * 6378.137 //地球半径
				s = Math.round(s * 10000) / 10000
				return s
			},
			// 计算最近的距离
			nearDistance(array, centerLatitude, centerLongitude) {
				let temp = []
				for (let i = 0, l = array.length; i < l; i++) {
					const element = array[i]
					let d = this.distance(
						element.latitude,
						element.longitude,
						centerLatitude,
						centerLongitude
					)
					temp.push(d)
				}
				this.distanceL = Math.min.apply(null, temp)
			},
			toMapAPP(e) {
				let that = this
				// 获取用户是否开启 授权获取当前的地理位置、速度的权限。
				uni.getSetting({
					success(res) {
						console.log(res,'----1')
						// 如果没有授权
						if (!res.authSetting['scope.userLocation']) {
							// 则拉起授权窗口
							uni.authorize({
								scope: 'scope.userLocation',
								success() {
									//如果授权了
									const latitude = Number(e.lat)
									const longitude = Number(e.lng)
									that.latitude = res.latitude
									that.longitude = res.longitude
									// 标记是否授权
									that.isGps = true
									uni.openLocation({
										latitude: latitude, //到达的纬度
										longitude: longitude, //到达的经度
										name: e.address, //到达的名字
										scale: 12,
										success() {
											console.log('success')
										}
									})
								},
								fail(error) {
									//点击了拒绝授权后--就一直会进入失败回调函数--此时就可以在这里重新拉起授权窗口
									console.log('拒绝授权', error)
 
									uni.showModal({
										title: '提示',
										content: '若点击不授权，将无法使用位置功能',
										cancelText: '不授权',
										cancelColor: '#999',
										confirmText: '授权',
										confirmColor: '#f94218',
										success(res) {
											console.log(res)
											if (res.confirm) {
												// 选择弹框内授权
												uni.openSetting({
													success(res) {
														console.log(res.authSetting)
													}
												})
											} else if (res.cancel) {
												// 选择弹框内 不授权
												console.log('用户点击不授权')
											}
										}
									})
								}
							})
						} else {
							console.log('有授权');
							// 有权限则直接获取
							uni.getLocation({
								type: 'gcj02',
								success: function(res) {
									const latitude = Number(e.lat)
									const longitude = Number(e.lng)
									uni.openLocation({
										latitude: latitude, //到达的纬度
										longitude: longitude, //到达的经度
										name: e.address, //到达的名字
										scale: 12,
										success() {
											console.log('success')
										}
									})
								},
								fail(error) {
									uni.showToast({
										title: '请先打开GPS位置服务！',
										icon: 'none',
									})
									console.log('失败', error)
								}
							})
						}
					}
				})
			}
		}
	}
</script>

<style lang="less">
#activeMap{
	height: 100vh;
}

// 设置图片样式
.manpCenter {
  width: 56rpx;
  height: 96rpx;
  position: absolute;
  left: calc(50% - 28rpx);
  top: calc(50% - 48rpx); // 按道理是-38.5rpx，但是会比实际偏上一点，设置-77rpx视觉上比较符合实际
}

.map-box{
	.map_tisp{
		position: fixed;
		top: 0;
		width: 100%;
		z-index: 99;
		background: #fff;
		padding: 10rpx;
	}
	.f-cont{
		width: 686rpx;
		height: 330rpx;
		background: #FFFFFF;
		box-shadow: 0rpx 16rpx 64rpx 0rpx rgba(0,0,0,0.16);
		border-radius: 44rpx;
		position: absolute;
		bottom: 184rpx;
		left: 50%;
		margin-left: -343rpx;
		z-index: 9;
	}
	.info{
		display: flex;
		.img{
			width: 200rpx;
			height: 200rpx;
			margin-top: 32rpx;
			margin-left: 32rpx;
			margin-right: 16rpx;
			border-radius: 16rpx;
			display: block;
		}
		.r-info{
			flex: 1;
			margin-top: 32rpx;
			margin-right: 10rpx;
		}
		.time{
			color: #666666;
			font-size: 28rpx;
			margin-top: 16rpx;
		}
		.mt{
			margin-top: 24rpx;
		}
		.s{
			width: 32rpx;
			height: 32rpx;
			margin-right: 8rpx;
			vertical-align: middle;
		}
	}
	.foot-info{
		display: flex;
		align-items: center;
		margin-left: 42rpx;
		margin-right: 34rpx;
		margin-top: 12rpx;
		.imgs{
			width: 36rpx;
			height: 50rpx;
			margin-right: 20rpx;
		}
		color: #3D3D3D;
		font-size: 32rpx;
		.fr{
			flex: 1;
			text-align: right;
		}
		.dh{
			width: 144rpx;
			height: 64rpx;
		}
	}
	
	.no-gps{
		display: flex;
		justify-content: center;
		align-items: center;
		flex-direction: column;
		height: 70vh;
		.no-gps-desc{
			font-size: 26rpx;
			color: #666;
		}
		.location_indicator {
		    margin: 0 auto;
		    width: 200rpx;
			height: 160rpx;
			position: relative;
		}
		.location_indicator:before, .location_indicator:after {
		    position: absolute;
		    content: "";
		}
		.location_indicator:before {
		    width: 20px;
		    height: 20px;
		    border-radius: 100% 100% 100% 0;
		    box-shadow: 0px 0px 0px 2px #666;
		    -webkit-animation: mapping 1s linear infinite;
		    -moz-animation: mapping 1s linear infinite;
		    animation: mapping 1s linear infinite;
		    -webkit-transform: rotate(-46deg);
		    -moz-transform: rotate(-46deg);
		    transform: rotate(-46deg);
			margin-left: 85rpx;
			margin-top: 40rpx;
		}
		.location_indicator:after {
		    width: 30px;
		    height: 10px;
		    border-radius: 100%;
		    left: 37px;
		    background-color: #ccc;
		    top: 47px;
		    z-index: -1;
		}
	}
	
	.fj-bnt{
		background-color: #E4919D;
		color: #fff;
		font-size: 28rpx;
		margin: 0 auto;
		width: 200rpx;
		padding: 16rpx 0;
		border-radius: 50rpx;
		text-align: center;
		margin-top: 35rpx;
	}
}
@keyframes mapping
{
    0%   {top: 0;}
    50%  {top: -5px;}
    100% {top: 0;}
}
@-webkit-keyframes mapping
{
    0%   {top: 0;}
    50%  {top: -5px;}
    100% {top: 0;}
}
</style>
